﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using System.Management;

namespace Shine.Framework
{ /// <summary>
    /// 作用：系统启动验证类
    /// 作者：叶茂
    /// 修改日期：2009-06-19
    /// </summary>
    public class StartupCheck
    {
        public static int GetOSBit()
        {

            try
            {
                string addressWidth = String.Empty;
                ConnectionOptions mConnOption = new ConnectionOptions();
                ManagementScope mMs = new ManagementScope(@"\\localhost", mConnOption);
                ObjectQuery mQuery = new ObjectQuery("select AddressWidth from Win32_Processor");
                ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(mMs, mQuery);
                ManagementObjectCollection mObjectCollection = mSearcher.Get();
                foreach (ManagementObject mObject in mObjectCollection)
                {
                    addressWidth = mObject["AddressWidth"].ToString();
                }
                return Int32.Parse(addressWidth);
            }
            catch (Exception ex)
            {
                return 32;
            }
        }
        /// <summary>
        /// 验证Engine是否安装，版本是否正确，补丁包是否已打
        /// </summary>
        /// <returns></returns>
        public static bool CheckEngine()
        {
            string wow="";
            if((GetOSBit()==64)) wow="Wow6432Node\\";

            //return true;
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey esrirk = rk.OpenSubKey("SOFTWARE\\" + wow + "ESRI\\Engine10.1\\CoreRuntime");
            //if (esrirk == null) esrirk = rk.OpenSubKey("SOFTWARE\\ESRI\\ArcGIS Engine SDK for .NET");
            if (esrirk == null) esrirk = rk.OpenSubKey("SOFTWARE\\" + wow + "ESRI\\Desktop10.1\\CoreRuntime");
            if (esrirk == null)
            {
                MessageBox.Show("软件运行需要ArcEngine的运行环境", "系统将退出");
                return false;
            }
            else
            {

                object value = esrirk.GetValue("RealVersion");
                if (value == null || value.ToString().StartsWith("10.1")==false )
                {
                    MessageBox.Show("软件运行需要ArcEngine9.3的运行环境", "系统将退出");
                    return false;
                }
                //else
                //{
                //    value = esrirk.GetValue("SpNumber");
                //    if (value == null || value.ToString() != "1")
                //    {
                //        MessageBox.Show("软件运行需要ArcEngine的sp1补丁", "系统将退出");
                //        return false;
                //    }
                //    else
                //        return true;
                //}
                return true;
            }
        }

        /// <summary>
        /// 验证Oracle数据库是否安装正确
        /// </summary>
        /// <returns></returns>
        public static bool CheckOracle()
        {
            try
            {
                string wow = "";
                if ((GetOSBit() == 64)) wow = "Wow6432Node\\";

                RegistryKey rk = Registry.LocalMachine;
                RegistryKey oraclerk = rk.OpenSubKey("SOFTWARE\\" + wow + "Oracle");
                if (oraclerk == null)
                {
                    //ZJGIS.ADF.BaseClasses.ControlUtility.ShowErrorMsgbox("软件运行需要Oracle客户端");
                    return false;
                }
                else
                {
                    string[] keynames = oraclerk.GetSubKeyNames();
                    bool isModified = false;
                    //DirectoryInfo info = new DirectoryInfo(Application.StartupPath + "\\Config\\");
                    //if (!info.Exists)
                    //{
                    //    info.Create();
                    //}
                    string folder = System.Configuration.ConfigurationManager.AppSettings.Get("Folder");
                    string filename;
                    if (folder == null || folder.Trim() == "")
                    {
                        filename = Application.StartupPath + "\\Config\\OracleConfigure.txt";
                    }
                    else
                    {
                        filename = Application.StartupPath + "\\" + folder + "\\Config\\OracleConfigure.txt";
                    }

                    //string filename = Application.StartupPath + "\\Config\\OracleConfigure.txt";
                    FileInfo fileinfo = new FileInfo(filename);
                    if (!fileinfo.Exists)
                    {
                      //  ZJGIS.ADF.BaseClasses.ControlUtility.ShowErrorMsgbox("Oracle配置文件未找到，请核查！");
                        return false;
                        //StreamWriter sw = File.CreateText(filename);
                        //sw.WriteLine("zjgis =");
                        //sw.WriteLine("  (DESCRIPTION =");
                        //sw.WriteLine("    (ADDRESS_LIST =");
                        //sw.WriteLine("      (ADDRESS = (PROTOCOL = TCP)(HOST = 10.33.0.253)(PORT = 1521))");
                        //sw.WriteLine("    )");
                        //sw.WriteLine("    (CONNECT_DATA =");
                        //sw.WriteLine("      (SERVICE_NAME = orcl)");
                        //sw.WriteLine("    )");
                        //sw.WriteLine("  )");
                        //sw.Close();
                    }
                    StreamReader sr1 = new StreamReader(filename);
                    string zjgisTNS = sr1.ReadToEnd();
                    sr1.Close();
                    foreach (string keyname in keynames)
                    {   
                        //modify by sheng  如果用户装的是Oracle服务器，也应该可以运行
                        string path = oraclerk.OpenSubKey(keyname).GetValue("ORACLE_HOME") as string;
                        if (path != null)
                        {
                            path = path + @"\NETWORK\ADMIN\tnsnames.ora";
                            if (File.Exists(path))
                            {
                                StreamReader sr = new StreamReader(path);
                                string content = sr.ReadToEnd();
                                sr.Close();
                                int index = zjgisTNS.ToLower().IndexOf("(HOST".ToLower());
                                string refString = zjgisTNS.Substring(0, index);
                                if (content.Contains(refString))
                                {
                                    int index1 = content.ToLower().IndexOf(refString.ToLower());

                                    int index2 = content.ToLower().IndexOf("SERVICE_NAME".ToLower(), index1);
                                    index2 = content.ToLower().IndexOf(")", index2);
                                    index2 = content.ToLower().IndexOf(")", index2 + 1);
                                    index2 = content.ToLower().IndexOf(")", index2 + 1);
                                    string tzgisTNSStr = content.Substring(index1, index2 - index1 + 1);
                                    content = content.Replace(tzgisTNSStr, zjgisTNS);
                                }
                                else
                                {
                                    content += zjgisTNS;
                                }
                                StreamWriter sw = new StreamWriter(path);
                                sw.Write(content);
                                sw.Close();
                                isModified = true;
                            }
                            else if (Directory.Exists(path.Replace(@"\tnsnames.ora", "")))
                            {
                                StreamWriter sw = File.CreateText(path);
                                sw.WriteLine(zjgisTNS);
                                sw.Close();
                                isModified = true;
                            }
                            else
                            {
                               // ZJGIS.ADF.BaseClasses.ControlUtility.ShowWarningMsgbox("您的计算机中安装了多个Oracle客户端，可能会影响系统的运行！推荐卸载多余的客户端后继续运行。");
                            }
                        }
                    }
                    if (isModified)
                    {
                        return true;
                    }
                   // ZJGIS.ADF.BaseClasses.ControlUtility.ShowErrorMsgbox("数据库网络服务配置失败，请联系管理员!");
                    return false;

                }
            }
            catch
            {
                return false;
            }
        }
    }
}
